// app/controllers/userController.js

const userModel = require('../models/userModel');

// 获取所有用户
exports.getAllUsers = (req, res) => {
  userModel.getAllUsers((err, results) => {
    if (err) return res.status(500).send('Database error');
    res.render('user', { users: results });
  });
};

// 根据 ID 获取用户
exports.getUserById = (req, res) => {
  const userId = req.params.id;
  userModel.getUserById(userId, (err, results) => {
    if (err) return res.status(500).send('Database error');
    if (results.length === 0) return res.status(404).send('User not found');
    res.json(results[0]);
  });
};

// 创建新用户
exports.createUser = (req, res) => {
  const { name, age, email } = req.body;
  userModel.createUser(name, age, email, (err, results) => {
    if (err) return res.status(500).send('Database error');
    res.redirect('/users');
  });
};


// 更新用户
exports.updateUser = (req, res) => {
  const { id } = req.params;
  const { name, age, email } = req.body;
  userModel.updateUser(id, name, age, email, (err) => {
    if (err) return res.status(500).send('Database error');
    res.redirect('/users');
  });
};

// 删除用户
exports.deleteUser = (req, res) => {
  const userId = req.params.id;
  userModel.deleteUser(userId, (err) => {
    if (err) return res.status(500).send('Database error');
    res.redirect('/users');
  });
};
// 显示编辑页面
exports.getEditUserPage = (req, res) => {
  const userId = req.params.id;
  userModel.getUserById(userId, (err, results) => {
    if (err) return res.status(500).send('数据库错误');
    if (results.length === 0) return res.status(404).send('用户未找到');
    res.render('editUser', { user: results[0] }); // 渲染 editUser.ejs 页面
  });
};
// 显示删除确认页面
exports.getDeleteUserPage = (req, res) => {
  const userId = req.params.id;
  userModel.getUserById(userId, (err, results) => {
    if (err) return res.status(500).send('数据库错误');
    if (results.length === 0) return res.status(404).send('用户未找到');
    res.render('deleteUser', { user: results[0] }); // 确保渲染 deleteUser.ejs
  });
};